//
//  NASearchBar.m
//  NewApp
//
//  Created by  on 12-7-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "NASearchBar.h"
#import <QuartzCore/QuartzCore.h>

@interface NASearchBar (Privates)

/**
 *  Build user interface
 */
- (void) buildUserInterface;

/**
 *  Search button did pressed
 */
- (void) toggleSearch;

@end

@implementation NASearchBar
@synthesize keywordTextfield,searchButton,delegate;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self buildUserInterface];
        
    }
    return self;
}

- (void) dealloc {
    [keywordTextfield release];
    [searchButton release];
    [super dealloc];
}


#pragma mark -
#pragma mark - Private methods

- (void) buildUserInterface {
    
    self.backgroundColor = [UIColor colorWithRed:0.33f green:0.33f blue:0.33f alpha:1.f];
    
    UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(10.f, 7.f,200.f,29.f)];
    tf.delegate = self;
    tf.clearButtonMode = UITextFieldViewModeWhileEditing;
    tf.backgroundColor = [UIColor whiteColor];
    tf.borderStyle = UITextBorderStyleRoundedRect;
    tf.font = [UIFont systemFontOfSize:17.f];
    tf.returnKeyType = UIReturnKeyDone;
    self.keywordTextfield = tf;
    [tf release];
    
    [self addSubview:self.keywordTextfield];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"search_icon.png"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"search_button.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(toggleSearch) forControlEvents:UIControlEventTouchUpInside];
    self.searchButton = btn;
    self.searchButton.imageEdgeInsets = UIEdgeInsetsMake(0.f, 0.f, 0.f, 10.f);
    [self.searchButton setTitle:@"搜尋" forState:UIControlStateNormal];
    self.searchButton.frame = CGRectMake(220.f, 5.f, 90.f, 34.f);
    [self addSubview:self.searchButton];
}

- (void) toggleSearch {
    if (self.delegate != nil) {
        if ([self.delegate respondsToSelector:@selector(searchButtonDidPressed)]) {
            [self.delegate searchButtonDidPressed];
        }
    }
}

#pragma mark -
#pragma mark - UITextfieldDelegate methods

- (BOOL) textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    
//    if (textField.text.length > 0) {
//        if (self.delegate != nil) {
//            if ([self.delegate respondsToSelector:@selector(searchButtonDidPressed)]) {
//                [self.delegate searchButtonDidPressed];
//            }
//        }
//
//    }
    
    return YES;
}


@end
